<script setup>
import { ref, reactive, toRaw, onMounted } from 'vue'
import { getAll, addApi, deleteApi ,queryByIdApi,updateApi} from '@/api/warehouse'
import { ElMessage } from 'element-plus'
import { getCityList } from '@/api/supplier'

const form = ref({
  name: '',
  cityName: '',
  personChargeName: ''
})

const formData = reactive({
  name: '',
  cityId: [], // 修改为数组，用于存储级联选择器的值
  address: '',
  personChargeName: '',
  isDel: ''
})

const cascaderOptions = ref([])
const tableData = ref([])
const currentPage = ref(1)
const total = ref(0)
const pageSize = ref(5)
const title = ref('')
const open = ref(false)

// 转换城市数据为级联选择器所需格式
const transformCategoryData = (data) => {
  return data.map(item => ({
    value: item.id,
    label: item.name,
    children: item.children && item.children.length > 0 ? transformCategoryData(item.children) : undefined
  }))
}

const onSubmit = async () => {
  const res = await getAll(form.value.name, form.value.cityName, form.value.personChargeName, currentPage.value, pageSize.value)
  tableData.value = res.data.rows
  total.value = res.data.total
}

const getcityList = async () => {
  try {
    const result = await getCityList()
    console.log('获取城市列表的响应:', result) // 添加调试信息
    
    if (result.code === 1 && result.data && result.data.length > 0) {
      cascaderOptions.value = transformCategoryData(result.data)
      console.log('级联选择器选项已设置:', cascaderOptions.value)
    } else {
      ElMessage.error('获取城市列表失败: 数据格式不正确')
      console.error('数据格式错误:', result)
    }
  } catch (error) {
    ElMessage.error('获取城市列表失败: ' + error.message)
    console.error(error)
  }
}

const clean = () => {
  form.value.name = ''
  form.value.cityName = ''
  form.value.personChargeName = ''
  onSubmit()
}

const add = () => {
  title.value = '新增仓库'
  open.value = true
  // 重置表单
  formData.name = ''
  formData.cityId = []
  formData.address = ''
  formData.personChargeName = ''
  formData.isDel = ''
}

const submitForm = async () => {
  // 处理表单提交
  try {
    // 构造提交数据
    const submitData = {
      ...formData,
      // 如果需要保存选中城市的完整路径，可以这样处理
      // cityPath: formData.cityId.join(','),
      // 如果只需要最后一级城市的ID，可以这样处理
      cityId: formData.cityId.length > 0 ? formData.cityId[formData.cityId.length - 1] : null
    }
    
    let res;
    // 根据是否存在ID判断是添加还是修改
    if (formData.id) {
      // 修改操作
      res = await updateApi(submitData)
    } else {
      // 添加操作
      res = await addApi(submitData)
    }
    
    if (res.code) {
      ElMessage.success(formData.id ? '修改成功' : '添加成功')
      open.value = false
      onSubmit()
    } else {
      ElMessage.error(formData.id ? '修改失败' : '添加失败')
    }
  } catch (error) {
    ElMessage.error((formData.id ? '修改失败' : '添加失败') + ': ' + error.message)
  }
}
const cancel=()=>{ 
  open.value = false
}
const handleUpdate=async(row)=>{
  title.value = '修改仓库'
  open.value = true
  try {
    const res = await queryByIdApi(row.id)
    console.log('获取到的仓库数据:', res.data)
    
    // 填充表单数据
    formData.id = res.data.id
    formData.name = res.data.name
    formData.address = res.data.address
    formData.personChargeName = res.data.personChargeName
    formData.isDel = res.data.isDel ? String(res.data.isDel) : ''
    
    // 处理城市级联选择器的回显
    if (res.data.cityId) {
      console.log('城市ID:', res.data.cityId)
      console.log('级联选项:', cascaderOptions.value)
      
      // 需要根据城市ID在cascaderOptions中查找完整路径
      const cityPath = findCityPath(cascaderOptions.value, res.data.cityId)
      console.log('查找的路径:', cityPath)
      formData.cityId = cityPath
    } else {
      formData.cityId = []
    }
  } catch (error) {
    ElMessage.error('获取仓库信息失败: ' + error.message)
    console.error(error)
  }
}
const handleDelete=async(row)=>{
  try {
    const res = await deleteApi(row.id)
    if (res.code) {
      ElMessage.success('删除成功')
      onSubmit()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message)
  }
}
// 根据城市ID在级联选项中查找完整路径
const findCityPath = (nodes, targetId, path = []) => {
  for (const node of nodes) {
    const currentPath = [...path, node.value]
    
    if (node.value === targetId) {
      return currentPath
    }
    
    if (node.children) {
      const result = findCityPath(node.children, targetId, currentPath)
      if (result.length > 0) {
        return result
      }
    }
  }
  return []
}
// 处理级联选择器值变化
const handleCascaderChange = (value) => {
  // value 是一个数组，包含选中项的所有值 [2, 1, 3] 对应 [湖北, 武汉, 武湖]
  console.log('级联选择器值变化:', value)
  // 可以根据需要处理选中的值，这里直接保存在 formData.cityId 中
}

onMounted(() => {
  onSubmit()
  getcityList()
})
</script>
<template>
  <el-button type="primary" @click="add">新增</el-button>
  <el-form :inline="true" :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="仓库名字">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="所在城市">
      <el-input v-model="form.cityName" />
    </el-form-item>
    <el-form-item label="负责人">
      <el-input v-model="form.personChargeName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
      <el-button @click="clean">取消</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column fixed prop="name" label="仓库名字" width="150" />
    <el-table-column prop="cityName" label="所在城市" width="120" />
    <el-table-column prop="address" label="详细地址" width="120" />
    <el-table-column prop="personChargeName" label="负责人" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="120" />
    <el-table-column prop="isDel" label="是否有效" width="120">
      <template #default="scope">
        <el-tag v-if="scope.row.isDel === 1" type="success">有效</el-tag>
        <el-tag v-else type="danger">无效</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" min-width="120">
     
       <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
  
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 10px; text-align: right;">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="projectRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="仓库名字" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="城市" prop="cityId">
        <div class="m-4">
          <el-cascader v-model="formData.cityId" 
          :options="cascaderOptions"
          :props="{ expandTrigger: 'hover' }"
          @change="handleCascaderChange"
          placeholder="请选择"
          style="width: 100%" />
        </div>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="personChargeName">
        <el-input v-model="formData.personChargeName" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="是否有效" prop="isDel">
        <el-select v-model="formData.isDel" clearable placeholder="请选择" style="width: 240px">
          <el-option label="有效" value="1" />
          <el-option label="无效" value="2" />
        </el-select>
      </el-form-item>


    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped></style>